package org.walkframework.sample.starter.config;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.walkframework.boot.application.SPIFactory;
import org.walkframework.boot.trace.TraceIdHolder;
import org.walkframework.boot.trace.TraceService;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 追踪ID监听器
 *
 * @author 尾生
 * @since 2023/8/23
 */
@Component
public class TraceIdListener implements Filter {

    private static final String TRACE_ID_HEADER = "X-TraceId";
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        TraceIdHolder.reset();
        String traceId = null;
        // 请求链路上下文中使用的traceId
        if (request instanceof HttpServletRequest) {
            traceId = ((HttpServletRequest) request).getHeader(TRACE_ID_HEADER);
        }
        if (StringUtils.isEmpty(traceId)) {
            // 生成traceId
            traceId = SPIFactory.getFirstService(TraceService.class).getTraceId();
        }
        TraceIdHolder.setTraceId(traceId);
        filterChain.doFilter(request, response);
    }
}
